package com.medical.standard.dao;

import com.medicalstandard.entity.DocumentTemplate;
import com.medicalstandard.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DocumentTemplateDAO {

    // 生成自动文档编号 (格式: DOC-yyyyMMdd-序号)
    private String generateDocumentNumber() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String datePart = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());

            // 查询今天的文档数量
            String countSql = "SELECT COUNT(*) FROM document_template WHERE document_number LIKE ?";
            pstmt = conn.prepareStatement(countSql);
            pstmt.setString(1, "DOC-" + datePart + "-%");
            rs = pstmt.executeQuery();

            int count = 0;
            if (rs.next()) {
                count = rs.getInt(1);
            }

            // 生成新编号
            String newNumber = "DOC-" + datePart + "-" + String.format("%03d", count + 1);
            return newNumber;

        } catch (SQLException e) {
            e.printStackTrace();
            // 如果生成失败，使用时间戳作为备用方案
            return "DOC-" + System.currentTimeMillis();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
    }

    // 创建新文档
    public boolean createDocument(DocumentTemplate document) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();

            // 生成文档编号
            String documentNumber = generateDocumentNumber();
            document.setDocumentNumber(documentNumber);

            String sql = "INSERT INTO document_template (document_number, product_name, product_model, " +
                    "standard_id, performance_indicators, inspection_methods, product_specification, " +
                    "terminology, created_by, create_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, document.getDocumentNumber());
            pstmt.setString(2, document.getProductName());
            pstmt.setString(3, document.getProductModel());
            pstmt.setInt(4, document.getStandardId());
            pstmt.setString(5, document.getPerformanceIndicators());
            pstmt.setString(6, document.getInspectionMethods());
            pstmt.setString(7, document.getProductSpecification());
            pstmt.setString(8, document.getTerminology());
            pstmt.setString(9, document.getCreatedBy());
            pstmt.setTimestamp(10, new Timestamp(document.getCreateDate().getTime()));
            pstmt.setString(11, document.getStatus());

            int result = pstmt.executeUpdate();
            return result > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt);
        }
    }

    // 更新文档
    public boolean updateDocument(DocumentTemplate document) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE document_template SET product_name=?, product_model=?, standard_id=?, " +
                    "performance_indicators=?, inspection_methods=?, product_specification=?, " +
                    "terminology=?, status=? WHERE document_id=?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, document.getProductName());
            pstmt.setString(2, document.getProductModel());
            pstmt.setInt(3, document.getStandardId());
            pstmt.setString(4, document.getPerformanceIndicators());
            pstmt.setString(5, document.getInspectionMethods());
            pstmt.setString(6, document.getProductSpecification());
            pstmt.setString(7, document.getTerminology());
            pstmt.setString(8, document.getStatus());
            pstmt.setInt(9, document.getDocumentId());

            int result = pstmt.executeUpdate();
            return result > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt);
        }
    }

    // 删除文档
    public boolean deleteDocument(int documentId) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM document_template WHERE document_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, documentId);

            int result = pstmt.executeUpdate();
            return result > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt);
        }
    }

    // 根据ID获取文档
    public DocumentTemplate getDocumentById(int documentId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        DocumentTemplate document = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM document_template WHERE document_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, documentId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                document = new DocumentTemplate();
                document.setDocumentId(rs.getInt("document_id"));
                document.setDocumentNumber(rs.getString("document_number"));
                document.setProductName(rs.getString("product_name"));
                document.setProductModel(rs.getString("product_model"));
                document.setStandardId(rs.getInt("standard_id"));
                document.setPerformanceIndicators(rs.getString("performance_indicators"));
                document.setInspectionMethods(rs.getString("inspection_methods"));
                document.setProductSpecification(rs.getString("product_specification"));
                document.setTerminology(rs.getString("terminology"));
                document.setCreatedBy(rs.getString("created_by"));
                document.setCreateDate(rs.getTimestamp("create_date"));
                document.setStatus(rs.getString("status"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return document;
    }

    // 获取用户创建的所有文档
    public List<DocumentTemplate> getDocumentsByUser(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<DocumentTemplate> documents = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM document_template WHERE created_by=? ORDER BY create_date DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                DocumentTemplate document = new DocumentTemplate();
                document.setDocumentId(rs.getInt("document_id"));
                document.setDocumentNumber(rs.getString("document_number"));
                document.setProductName(rs.getString("product_name"));
                document.setProductModel(rs.getString("product_model"));
                document.setStandardId(rs.getInt("standard_id"));
                document.setPerformanceIndicators(rs.getString("performance_indicators"));
                document.setInspectionMethods(rs.getString("inspection_methods"));
                document.setProductSpecification(rs.getString("product_specification"));
                document.setTerminology(rs.getString("terminology"));
                document.setCreatedBy(rs.getString("created_by"));
                document.setCreateDate(rs.getTimestamp("create_date"));
                document.setStatus(rs.getString("status"));
                documents.add(document);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return documents;
    }

    // 获取所有文档
    public List<DocumentTemplate> getAllDocuments() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<DocumentTemplate> documents = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM document_template ORDER BY create_date DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                DocumentTemplate document = new DocumentTemplate();
                document.setDocumentId(rs.getInt("document_id"));
                document.setDocumentNumber(rs.getString("document_number"));
                document.setProductName(rs.getString("product_name"));
                document.setProductModel(rs.getString("product_model"));
                document.setStandardId(rs.getInt("standard_id"));
                document.setPerformanceIndicators(rs.getString("performance_indicators"));
                document.setInspectionMethods(rs.getString("inspection_methods"));
                document.setProductSpecification(rs.getString("product_specification"));
                document.setTerminology(rs.getString("terminology"));
                document.setCreatedBy(rs.getString("created_by"));
                document.setCreateDate(rs.getTimestamp("create_date"));
                document.setStatus(rs.getString("status"));
                documents.add(document);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return documents;
    }
}